import json

from django.contrib.auth import login
from django.shortcuts import render, redirect
from django.urls import reverse

from django.views import View
from django import http
import re

from django_redis import get_redis_connection

from apps.goods.models import SKU
from apps.users.models import User, Address
from apps.users.utils import generate_verify_email_url
from utils.cookiesecret import CookieSecret
from utils.response_code import RETCODE


class RegisterView(View):
    def get(self, request):
        """
        提供注册界面
        :param request: 请求对象
        :return: 注册界面
        """

        return render(request, 'register.html')

    def post(self, request):
        """
        实现用户注册
        :param request: 请求对象
        :return: 注册结果
        """
        # 1.接受参数
        username = request.POST.get('username')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        mobile = request.POST.get('mobile')

        # sms_code
        allow = request.POST.get('allow')

        # 2.校验
        if not all([username, password, password2, mobile]):
            return http.HttpResponseForbidden('缺少参数！')

        # 3.用户名：正则校验-判断重复
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return http.HttpResponseForbidden('请输入5-20个字符的用户名')
        # 判断密码是否是8-20个数字
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.HttpResponseForbidden('请输入8-20位的密码')
        # 判断两次密码是否一致
        if password != password2:
            return http.HttpResponseForbidden('两次输入的密码不一致')
        # 判断手机号是否合法
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('请输入正确的手机号码')
        # 判断是否勾选用户协议
        if allow != 'on':
            return http.HttpResponseForbidden('请勾选用户协议')

        # 判断短信验证码是否正确
        sms_code = request.POST.get('msg_code')

        redis_sms_client = get_redis_connection('sms_code')
        redis_sms_code = redis_sms_client.get('sms_%s ' % mobile)
        if not redis_sms_code:
            return render(request, 'register.html', {'sms_code_errmsg': '无效的短信验证码'})
        redis_sms_client.delete('sms_%s ' % mobile)
        if sms_code != redis_sms_code.decode():
            return render(request, 'register.html', {'sms_code_errmsg': '输入短信验证码有误'})
        # 3.注册
        user = User.objects.create_user(username=username, password=password, mobile=mobile)

        # 4.保持登录状态
        login(request, user)

        # 5.重定向
        response = redirect(reverse('contents:index'))
        response.set_cookie('username', user.username, max_age=3600 * 24 * 15)
        return response


# 2.判断用户名是否重复
class UsernameCountView(View):
    def get(self, request, username):
        # 1.接收参数

        # 2.校验是否为空
        # 3.业务逻辑判断
        count = User.objects.filter(username=username).count()
        # 4.返回相应对象
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'count': count})


# 3.判断手机号是否重复
class MobileCountView(View):
    """判断手机号是否重复注册"""

    def get(self, request, mobile):
        """
        :param request: 请求对象
        :param mobile: 手机号
        :return: JSON
        """
        count = User.objects.filter(mobile=mobile).count()
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'count': count})


# 4.用户名登录
class LoginView(View):
    def get(self, request):
        # 提供登录页面
        return render(request, 'login.html')

    def post(self, request):
        # 提交的是表单，所以用post
        # 接收三个参数，用户名，密码，保持登录状态
        username = request.POST.get('username')
        password = request.POST.get('password')
        remembered = request.POST.get('remembered')
        # 2.校验参数 是否为空
        if not all([username, password, remembered]):
            return http.HttpResponse('缺少参数！')
        # 2.1 用户名
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return http.HttpResponseForbidden('请输入5-20个字符的用户名')
        # 2.2 密码
        if not re.match(r'^[0-9a-zA-Z]{8,20}$', password):
            return http.HttpResponseForbidden('请输入8-20位的密码')
        # 3.验证用户名和密码--django自带的认证
        from django.contrib.auth import authenticate, login
        user = authenticate(request, username=username, password=password)
        if user is None:
            return render(request, 'login.html', {'account_errmsg': '用户名或密码错误'})
        # 4.保持登录状态
        login(request, user)
        # 5.是否记住用户名
        if remembered != 'on':
            request.session.set_expiry(0)
        else:
            request.session.set_expiry(None)

        # 操作next
        next = request.GET.get('next')
        if next:
            response = redirect(next)
        # 6.返回响应结果
        else:
            response = redirect(reverse('contents:index'))

        response.set_cookie('username', user.username, max_age=3600 * 24 * 15)

        # 登录成功————合并购物车
        from apps.carts.utils import merge_cart_cookie_to_redis
        merge_cart_cookie_to_redis(request, response)

        return response


# 5.用户退出
class LogOutView(View):
    def get(self, request):
        # 清除登录状态
        from django.contrib.auth import logout
        logout(request)
        # 清除用户名username --cookie
        response = redirect(reverse('contents:index'))
        response.delete_cookie('username')

        return response


# 6.用户中心
from django.contrib.auth.mixins import LoginRequiredMixin


class UserInfoView(LoginRequiredMixin, View):
    def get(self, request):
        """提供个人信息界面"""
        context = {
            'username': request.user.username,
            'mobile': request.user.mobile,
            'email': request.user.email,
            'email_active': request.user.email_active
        }
        return render(request, 'user_center_info.html', context=context)


# 7.保存邮箱
class EmailView(LoginRequiredMixin, View):
    def put(self, request):
        # 1.接收参数
        json_dict = json.loads(request.body.decode())
        email = json_dict.get('email')
        # 2.校验
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return http.HttpResponseForbidden('参数email有误')

        # 3.修改邮箱 email
        try:
            request.user.email = email
            request.user.save()
        except Exception as e:
            print(e)
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '添加邮箱失败'})
        # 发邮件
        verify_url = generate_verify_email_url(request.user)
        from celery_tasks.email.tasks import send_verify_email
        send_verify_email.delay(email, verify_url)
        # 4.返回相应对象

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '添加邮箱成功'})


# 8.激活邮箱
class EmailVerifyView(View):
    def get(self, request):
        # 1.接收参数
        user_id = request.GET.get('user_id')
        email = request.GET.get('email')

        # 2.校验
        try:
            user = User.objects.get(id=user_id, email=email)
        except Exception as e:
            print(e)
            return http.HttpResponseForbidden('token是无效的')
        # 3.修改 email_acttive
        user.email_active = True
        user.save()

        return redirect(reverse('users:info'))


# 9.展示收货地址
class AddressView(View):
    def get(self, request):
        # 1.根据用户， 查询所有地址filter()
        addresses = Address.objects.filter(user=request.user, is_deleted=False)
        # 2.转换前端的数据格式
        addresses_list = []
        for address in addresses:
            addresses_list.append({
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
            })
            context = {
                'default_address_id': request.user.default_address_id,
                'addresses': addresses_list,
            }

        return render(request, 'user_center_site.html', context)


# 10.增加收货地址
class CreateAddressView(LoginRequiredMixin, View):
    def post(self, request):
        # 限制增加个数不能超过二十个
        count = Address.objects.filter(user=request.user).count()
        # count = request.user.addresses.filter(is_deleted=False).count()
        if count > 20:
            return http.JsonResponse({'code': RETCODE.THROTTLINGERR, 'errmsg': '超过地址数量上限'})

        # 1.接收参数 form Json
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')
        # 2.校验
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return http.HttpResponseForbidden('缺少必传参数')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('参数mobile有误')
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.HttpResponseForbidden('参数tel有误')
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.HttpResponseForbidden('参数email有误')
        # 3.orm = create() save()
        address = Address.objects.create(
            user=request.user,
            title=receiver,
            receiver=receiver,
            province_id=province_id,
            city_id=city_id,
            district_id=district_id,
            place=place,
            mobile=mobile,
            tel=tel,
            email=email,
        )
        # 设置默认地址
        if not request.user.default_address:
            request.user.default_address = address
            request.user.save()
        # 4.数据转换->dict
        data_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        # 响应保存结果
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '新增地址成功', 'address': data_dict})


# 12.保存用户记录
class UserBrowserView(LoginRequiredMixin, View):
    def post(self, request):

        # 1.接收参数
        sku_id = json.loads(request.body.decode())['sku_id']
        # 2.校验
        try:
            sku = SKU.objects.get(id=sku_id)
        except:
            return http.HttpResponseForbidden('商品不存在')
        # 3.链接redis
        client = get_redis_connection('history')
        redis_key = 'history_%d' % request.user.id

        # 管道优化
        p1 = client.pipeline()
        # 4.去重
        p1.lrem(redis_key, 0, sku_id)
        # 5.存
        p1.lpush(redis_key, sku_id)

        # 6.截取
        p1.ltrim(redis_key, 0, 4)

        p1.execute()
        # 7.存完了
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})

    def get(self, request):
        # 1.从reids链接
        client = get_redis_connection('history')
        # 2.lrange
        sku_ids = client.lrange('history_%d' % request.user.id, 0, -1)
        # 3.通过sku_id获得商品skus
        skus = []
        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)
            # 4.skus符合前端的数据格式
            skus.append({
                'id': sku.id,
                'name': sku.name,
                'default_image_url': sku.default_image.url,
                'price': sku.price
            })
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'skus': skus})


# 13.忘记密码
class FindPasswordView(View):
    def get(self, request):
        return render(request, 'find_password.html')


# 14.验证用户是否存在
class FindUsernameView(View):
    def get(self, request, username):
        image_code = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')

        try:
            user = User.objects.get(username=username)
        except:
            return http.JsonResponse({'status': 5004})

        from django_redis import get_redis_connection
        image_redis_client = get_redis_connection('verify_image_code')
        redis_img_code = image_redis_client.get('img_%s' % uuid)

        if image_code.lower() != redis_img_code.decode().lower():
            return http.JsonResponse({'status': 5001})

        mobile = user.mobile
        access_token = 'asd'
        access_token_str = CookieSecret.dumps(access_token)
        return http.JsonResponse({'status': 5000, 'mobile': mobile, 'access_token': access_token_str})


# 15.接收短信验证码
class GetMessageView(View):
    def get(self, request, mobile):
        access_token = request.GET.get('access_token')

        access_token_str = CookieSecret.loads(access_token)
        if access_token_str != 'asd':
            return http.JsonResponse({'status': 5001})

        # 生成短信验证码，redis存储
        from random import randint
        sms_code = "%06d" % randint(0, 999999)
        sms_redis_client = get_redis_connection('sms_code')
        sms_redis_client.setex("sms_%s" % mobile, 300, sms_code)

        print("当前验证码是:", sms_code)

        return http.JsonResponse({'status': 5000, "message": "短信发送成功"})


# 16.提交短信验证码
class PushView(View):
    def get(self, request, mobile):
        sms_code = request.GET.get('sms_code')
        from django_redis import get_redis_connection
        redis_code_client = get_redis_connection('sms_code')
        redis_code = redis_code_client.get('sms_%s' % mobile)

        if sms_code != redis_code.decode():
            return http.JsonResponse({'status': 5001})

        user = User.objects.get(mobile=mobile)

        access_token = 'asd'

        return http.JsonResponse({'status': 5000, 'user_id': user.id, 'access_token': access_token})


# 17.提交新密码
class PushNewpwdView(View):
    def post(self, request, user_id):
        json_dict = json.loads(request.body.decode())
        password = json_dict.get('password')
        password2 = json_dict.get('password2')
        access_token = json_dict.get('access_token')

        if not all([password, password2]):
            return http.HttpResponseForbidden('参数不能为空')

        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.HttpResponseForbidden('请输入8-20位的密码')

        if password2 != password:
            return http.HttpResponseForbidden('两次密码输入不一致')

        if access_token != 'asd':
            return http.JsonResponse({'status': 5001, 'message': 'token有误！'})

        try:
            user = User.objects.get(id=user_id)
        except:
            return http.JsonResponse({'status': 5002, 'message': 'user_id有误！'})

        user.set_password(password)
        user.save()

        return http.JsonResponse({'status': 5000, 'message': '密码修改成功'})
